import React, { PureComponent, Fragment } from 'react'
import { Trans, withI18n } from '@lingui/react'
import { connect } from 'dva'
import { Button, Icon, Tooltip, Divider, Tag, Card, InputNumber } from 'antd'
import { Page, ScrollBar } from 'components'
import styles from './NetWorks.less'

const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1315809_rku89owijgs.js',
})

const SliceImei = Imei => {
  if (Imei) {
    return Imei.length > 10
      ? `${Imei.slice(0, 4)}...${Imei.slice(Imei.length - 9, Imei.length)}`
      : Imei
  } else {
    return undefined
  }
}

const MakeImeiTag = item => {
  if (!item) {
    return null
  }
  const { geo, Imei, isMain } = item
  return (
    <Tag color={isMain ? 'magenta' : 'blue'} style={{ margin: 0 }}>
      <IconFont
        type={isMain ? 'icon-jizhanguanli' : 'icon-ludeng'}
        style={{ marginRight: 5 }}
      />
      {SliceImei(Imei)}
    </Tag>
  )
}
var EARTH_RADIUS = 6378137.0
var PI = Math.PI
function getRad(d) {
  return (d * PI) / 180.0
}
function getFlatternDistance(lat1, lng1, lat2, lng2) {
  var f = getRad((lat1 + lat2) / 2)
  var g = getRad((lat1 - lat2) / 2)
  var l = getRad((lng1 - lng2) / 2)

  var sg = Math.sin(g)
  var sl = Math.sin(l)
  var sf = Math.sin(f)

  var s, c, w, r, d, h1, h2
  var a = EARTH_RADIUS
  var fl = 1 / 298.257

  sg = sg * sg
  sl = sl * sl
  sf = sf * sf

  s = sg * (1 - sl) + (1 - sf) * sl
  c = (1 - sg) * (1 - sl) + sf * sl

  w = Math.atan(Math.sqrt(s / c))
  r = Math.sqrt(s * c) / w
  d = 2 * w * a
  h1 = (3 * r - 1) / 2 / c
  h2 = (3 * r + 1) / 2 / s

  const ret = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg))
  return ret ? (
    <span>{`${(ret / 1000).toFixed(2)}Km`}</span>
  ) : (
    <Trans>None</Trans>
  )
}
@withI18n()
@connect(({ loading }) => {
  const setloading = loading.effects[`loras/setNetWork`]
  return { setloading }
})
class Toolbox extends PureComponent {
  shouldComponentUpdate(nextprops, nextstate) {
    return (
      nextprops.tmpedited != this.props.tmpedited ||
      nextprops.scal != this.props.scal ||
      nextstate.hovered_Btn != this.state.hovered_Btn
    )
  }
  state = {
    hovered_Btn: undefined,
  }
  render() {
    console.log('Toolbox render')
    const {
      tmpedited,
      scal,
      onSetNetwork,
      changescal,
      clearedit,
      relocation,
      setloading,
      dispatch,
      i18n,
    } = this.props
    const { hovered_Btn } = this.state
    const toolsize = {
      height: 27,
      width: 27,
    }
    const toolstyle = {
      ...toolsize,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: 5,
      cursor: 'pointer',
      color: 'rgb(108,108,108)',
    }
    const hoveredstyle = {
      borderStyle: 'solid',
      borderWidth: 1,
      borderRadius: 5,
      borderColor: 'rgba(230,233,237,1)',
    }
    const nohoverstyle = {
      borderStyle: 'solid',
      borderWidth: 1,
      borderColor: 'rgba(230,233,237,0)',
    }
    const disablestyle = {
      ...toolstyle,
      cursor: 'not-allowed',
      color: 'rgb(190,190,190)',
    }
    const getstyle = (key, enable = true) => {
      return {
        ...toolstyle,
        ...(hovered_Btn == key ? hoveredstyle : nohoverstyle),
        ...(enable ? {} : disablestyle),
      }
    }
    const getEvent = key => {
      return {
        onMouseEnter: e => {
          this.setState({ hovered_Btn: key })
        },
        onMouseLeave: e => {
          this.setState({ hovered_Btn: undefined })
        },
      }
    }
    return (
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          borderStyle: 'solid',
          borderWidth: 1,
          borderColor: 'rgb(230,233,237)',
          height: 45,
          paddingLeft: 10,
          paddingRight: 10,
        }}
      >
        <Tooltip title={i18n.t`Zoom In`} placement="top">
          <div
            style={getstyle('Zoom In')}
            {...getEvent('Zoom In')}
            onClick={e => {
              changescal(scal + 0.01)
            }}
          >
            <Icon type="zoom-in" />
          </div>
        </Tooltip>
        <Tooltip title={i18n.t`Zoom Out`} placement="top">
          <div
            style={getstyle('Zoom Out')}
            {...getEvent('Zoom Out')}
            onClick={e => {
              changescal(scal - 0.01 <= 0.01 ? 0.01 : scal - 0.01)
            }}
          >
            <Icon type="zoom-out" />
          </div>
        </Tooltip>
        <Divider
          type="vertical"
          style={{ background: 'rgba(232,232,232,1)' }}
        />
        <Tooltip title={i18n.t`Locate at Project Center`} placement="top">
          <div
            style={getstyle('Locate at Project Center')}
            {...getEvent('Locate at Project Center')}
            onClick={e => {
              relocation()
            }}
          >
            <Icon type="environment" />
          </div>
        </Tooltip>
        <Divider
          type="vertical"
          style={{ background: 'rgba(232,232,232,1)' }}
        />
        {/* <Button
          style={{ height: toolsize.height, marginRight: 5 }}
          onClick={clearedit}
          type={'dashed'}
          disabled={!tmpedited || Object.keys(tmpedited).length <= 0}
          size="small"
        >
          <Icon type="delete" style={{ marginRight: 5 }} />
          <Trans>Clear Selection</Trans>
        </Button>
        <Button
          style={{ height: toolsize.height }}
          type={'primary'}
          disabled={!tmpedited || Object.keys(tmpedited).length <= 0}
          size="small"
          loading={setloading}
          onClick={e => {
            if (onSetNetwork) onSetNetwork(tmpedited)
          }}
        >
          <Icon type="save" style={{ marginRight: 5 }} />
          <Trans>Save</Trans>
        </Button> */}
        <Divider
          type="vertical"
          style={{ background: 'rgba(232,232,232,1)' }}
        />
        <Tooltip title={i18n.t`Download all networking logic`} placement="top">
          <Button
            style={{ height: toolsize.height, marginRight: 5 }}
            // onClick={clearedit}
            type={'danger'}
            size="small"
          >
            <IconFont type="icon-yunduanshuaxin" />
          </Button>
        </Tooltip>
      </div>
    )
  }
}

@withI18n()
@connect(({ loading }) => {
  const setloading = loading.effects[`loras/setNetWork`]
  return { setloading }
})
class SideBar extends PureComponent {
  state = {
    hoveredCard: -1,
    channelNeedSave: false,
    tmpChannel: undefined,
    Remain: false,
  }

  shouldComponentUpdate(nextprops, nextstate) {
    if (this.props.clicked != nextprops.clicked) {
      // if(nextprops.clicked){
      this.setState({ channelNeedSave: false, tmpChannel: undefined })
      // }
    }
    return (
      this.props.clicked != nextprops.clicked ||
      this.props.tmpedited != nextprops.tmpedited ||
      this.props.tmpdeleted != nextprops.tmpdeleted ||
      this.props.tmpchannels != nextprops.tmpchannels ||
      this.props.hovered != nextprops.hovered ||
      //
      this.state.hoveredCard != nextstate.hoveredCard ||
      this.state.channelNeedSave != nextstate.channelNeedSave ||
      this.state.tmpChannel != nextstate.tmpChannel ||
      this.state.Remain != nextstate.Remain
    )
  }

  render() {
    const {
      setloading,
      clicked,
      hovered,
      mapPointTocanvas,
      tmpedited,
      onDeleteLine,
      onSetNetwork,
      onHover,
      clearedit,
      // tmpdeleted,
      // tmpchannels,
      dispatch,
      i18n,
    } = this.props
    const { hoveredCard, tmpChannel, channelNeedSave, Remain } = this.state
    const makeChannelView = item => {
      var { Channel, isMain, Imei } = item
      return (
        // isMain &&
        <Fragment>
          <div
            style={{
              fontSize: 17,
              fontWeight: 'bold',
              marginBottom: 5,
              marginTop: 10,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <div>
              <Trans>Node Channel</Trans>:{' '}
            </div>
            <div>
              <Button
                size="small"
                type={Remain ? 'primary' : 'danger'}
                onClick={e => {
                  this.setState({ Remain: !Remain })
                }}
              >
                {Remain ? <Icon type="check" /> : <Icon type="stop" />}&nbsp;
                <Trans>Reserved band</Trans>
              </Button>
            </div>
          </div>
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              marginTop: 5,
            }}
          >
            <InputNumber
              size="small"
              value={
                tmpChannel != undefined
                  ? tmpChannel
                  : Channel != undefined
                  ? Channel
                  : 1
              }
              min={1}
              max={130}
              onChange={value => {
                this.setState({ tmpChannel: value })
              }}
              style={{ width: 80, marginRight: 5 }}
            />
            {
              <Button
                disabled={
                  tmpChannel == undefined || `${tmpChannel}` == `${Channel}`
                }
                size="small"
                onClick={e => {
                  dispatch({
                    type: 'loras/setChannel',
                    payload: {
                      Imei,
                      Channel: tmpChannel,
                      Remain: Remain ? 1 : 0,
                    },
                  })
                }}
              >
                <Trans>Save</Trans>
              </Button>
            }
          </div>
        </Fragment>
      )
    }
    const resolvePoint = item => {
      if (!item) return null
      const hoverstyle = {
        width: '100%',
      }
      const { geo, Imei, isMain } = item
      const p = mapPointTocanvas(geo)
      return (
        <div style={{ ...hoverstyle, left: p.x, top: p.y }}>
          <div style={{ fontSize: 17, fontWeight: 'bold', marginBottom: 10 }}>
            <Trans>Device Detail</Trans>:
          </div>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            {MakeImeiTag(item)}
          </div>
          {makeChannelView(item)}
        </div>
      )
    }
    const resolveLine = item => {
      if (!item) return null
      const hoverstyle = {
        width: '100%',
      }
      const { geo, Imei, parent, isMain, IsLined, isTmpEdit } = item
      const p = mapPointTocanvas(geo)
      const fromp = MakeImeiTag(item)
      const top = parent && MakeImeiTag(parent)
      const TagFilter = {
        '0': (
          <Tag color="gray">
            <IconFont type="icon-jichuguanli" />
            &nbsp;<Trans>Unconnected</Trans>
          </Tag>
        ),
        '1': (
          <Tag color="#87d068">
            <IconFont type="icon-jichuguanli" />
            &nbsp;<Trans>Connection Successful</Trans>
          </Tag>
        ),
        '-1': (
          <Tag color="#f50">
            <IconFont type="icon-jichuguanli" />
            &nbsp;<Trans>Connection Failed</Trans>
          </Tag>
        ),
        '-2': (
          <Tag color="#f50">
            <IconFont type="icon-jichuguanli" />
            &nbsp;<Trans>Connection Timed Out</Trans>
          </Tag>
        ),
        '-3': (
          <Tag color="rgb(250,170,20)">
            <Icon type="loading" />
            &nbsp;<Trans>Connecting</Trans>
          </Tag>
        ),
      }
      return (
        <div style={{ ...hoverstyle }}>
          <div
            style={{
              fontSize: 17,
              fontWeight: 'bold',
              marginBottom: 10,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <div>
              <Trans>Details of networking</Trans>:
            </div>
            <div style={{ fontSize: 14, fontWeight: 'normal' }}>
              {parent &&
                item &&
                item.geo &&
                parent.geo &&
                getFlatternDistance(
                  parseFloat(item.geo.x),
                  parseFloat(item.geo.y),
                  parseFloat(parent.geo.x),
                  parseFloat(parent.geo.y)
                )}
            </div>
          </div>
          <div>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              {fromp}
            </div>
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                marginTop: 5,
                fontSize: 17,
                color:
                  IsLined == '1'
                    ? LinedSuccessTagColor
                    : isTmpEdit
                    ? 'rgb(158,158,158)'
                    : 'rgb(102,102,102)',
              }}
            >
              {TagFilter[`${IsLined}`]}
            </div>
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                marginTop: 5,
              }}
            >
              {top}
            </div>
          </div>
          {makeChannelView(item)}
          <div
            style={{
              fontSize: 17,
              fontWeight: 'bold',
              marginBottom: 5,
              marginTop: 10,
            }}
          >
            <Trans>Node Operation</Trans>:
          </div>
          <div
            style={{
              marginTop: 10,
              width: '100%',
              display: 'flex',
              justifyContent: 'center',
            }}
          >
            <Button.Group
              size="default"
              style={{
                // width: '100%',
                display: 'flex',
                justifyContent: 'center',
              }}
            >
              <Button
                type={IsLined != '1' ? 'primary' : 'dashed'}
                disabled={IsLined == '0'}
                onClick={e => {
                  const targ = {}
                  targ[Imei] = item
                  onSetNetwork(targ)
                }}
              >
                <IconFont
                  type="icon-yunduanshuaxin"
                  style={{ marginRight: 5 }}
                />
                <Trans>Re-Set</Trans>
              </Button>
              <Button
                // disabled={isTmpEdit}
                type="dashed"
                style={{}}
                disabled={IsLined == '0'}
                onClick={e => {
                  if (onDeleteLine) {
                    onDeleteLine(item)
                  }
                }}
              >
                <Icon type="delete" style={{ marginRight: 5 }} />
                <Trans>Delete</Trans>
              </Button>
            </Button.Group>
          </div>
        </div>
      )
    }
    const resolveItem = item => {
      if (item) {
        const { parent } = item
        if (parent) {
          return resolveLine(item)
        } else {
          return resolvePoint(item)
        }
      }
      return null
    }
    var cardindex = 0
    const editList = () => {
      if (!tmpedited || Object.keys(tmpedited).length <= 0) return null
      var items = []
      for (const Imei in tmpedited) {
        const item = tmpedited[Imei]
        if (item && item.parent) {
          const { parent } = item
          //
          cardindex = cardindex + 1
          const tmpcardIndex = cardindex
          //
          items.push(
            <Card
              hoverable
              className={`tmpedit_${cardindex}`}
              style={{
                margin: 0,
                padding: 0,
                paddingLeft: 0,
                paddingRight: 0,
                marginBottom: 10,
                borderRadius: 10,
                borderWidth: 2,
                borderStyle: 'solid',
                borderColor:
                  hovered && hovered.Imei == Imei && hovered.isTmpEdit
                    ? 'rgb(24,144,255)'
                    : 'rgb(230,233,237)',
                height: 100,
                width: 175,
              }}
              bodyStyle={{
                margin: 0,
                padding: 0,
                height: 100,
                width: 175,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                position: 'relative',
                // paddingRight: 5,
              }}
              onMouseEnter={e => {
                this.setState({ hoveredCard: tmpcardIndex })
                if (onHover) {
                  onHover(item)
                }
              }}
              onMouseLeave={e => {
                this.setState({ hoveredCard: -1 })
                if (onHover) {
                  onHover(undefined)
                }
              }}
            >
              {
                <div style={{}}>
                  <div style={{ display: 'flex', justifyContent: 'center' }}>
                    {MakeImeiTag(item)}
                  </div>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'center',
                      marginTop: 5,
                      fontSize: 17,
                      color: 'rgb(158,158,158)',
                    }}
                  >
                    <IconFont type="icon-jichuguanli" />
                  </div>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'center',
                      marginTop: 5,
                    }}
                  >
                    {MakeImeiTag(parent)}
                  </div>
                </div>
              }
              {
                <div
                  style={{
                    width: '100%',
                    height: '100%',
                    position: 'absolute',
                    left: 0,
                    top: -2,
                    borderRadius: 10,
                    // borderWidth: 2,
                    // borderStyle: 'solid',
                    // borderColor: 'rgb(230,233,237)',
                    background: 'rgba(0,0,0,0.5)',
                    opacity: tmpcardIndex == hoveredCard ? 1 : 0,
                    transition: 'all 0.5s',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <div
                    type="ghost"
                    color="white"
                    style={{
                      height: 40,
                      width: 40,
                      marginRight: 10,
                      borderStyle: 'none',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                    className={styles.editIcon}
                    onClick={e => {
                      if (onSetNetwork) {
                        const targ = {}
                        targ[Imei] = item
                        onSetNetwork(targ)
                      }
                    }}
                  >
                    <IconFont type="icon-duigou" style={{ fontSize: 20 }} />
                  </div>
                  <div
                    style={{
                      width: 1,
                      height: 20,
                      background: 'white',
                      marginLeft: 10,
                      marginRight: 10,
                    }}
                  />
                  <div
                    type="ghost"
                    color="white"
                    style={{
                      height: 40,
                      width: 40,
                      borderStyle: 'none',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                    className={styles.editIcon}
                    onClick={e => {
                      if (onDeleteLine) {
                        onDeleteLine(item)
                      }
                    }}
                  >
                    <IconFont
                      type="icon-shanchusekuai"
                      style={{ fontSize: 20 }}
                    />
                  </div>
                </div>
              }
            </Card>
          )
        }
      }
      return items
    }
    const clickedView = resolveItem(clicked)
    const editView = editList()
    return (
      <div
        style={{
          width: 255,
          height: 'calc(100vh - 320px)',
          background: 'rgb(247,249,251)',
          padding: 10,
          paddingTop: 10,
          overflow: 'hidden',
          // position: 'relative'
        }}
      >
        {clickedView}
        {clickedView && editView && (
          <Divider
            style={{
              margin: 0,
              marginTop: 10,
              marginBottom: 5,
              background: 'rgb(188,188,188)',
            }}
          />
        )}
        {editView && (
          <div style={{ height: `${100}%` }}>
            <div
              style={{
                fontSize: 17,
                fontWeight: 'bold',
                marginBottom: 5,
                marginTop: 5,
                display: 'flex',
                justifyContent: 'space-between',
              }}
            >
              <Trans>Networking operation</Trans>:
              <Button
                style={{ marginRight: 5 }}
                onClick={e => {
                  clearedit()
                }}
                type={'danger'}
                disabled={!tmpedited || Object.keys(tmpedited).length <= 0}
                size="small"
              >
                <Icon type="delete" style={{ marginRight: 5 }} />
                <Trans>Clear Selection</Trans>
              </Button>
            </div>
            {/* <Button.Group style={{ marginBottom: 5 }}> */}
            {/* <Button
                style={{}}
                type={'primary'}
                disabled={!tmpedited || Object.keys(tmpedited).length <= 0}
                size="small"
                loading={setloading}
                onClick={e => {
                  if (onSetNetwork) onSetNetwork(tmpedited)
                }}
              >
                <Icon type="save" style={{ marginRight: 5 }} />
                <Trans>Save All</Trans>
              </Button> */}

            {/* </Button.Group> */}
            <ScrollBar
              option={{
                suppressScrollX: true,
              }}
            >
              {editView}
            </ScrollBar>
          </div>
        )}
      </div>
    )
  }
}

@withI18n()
class StatusBoard extends PureComponent {
  state = {}
  shouldComponentUpdate(nextprops, nextstate) {
    return this.props.hovered != nextprops.hovered
  }

  render() {
    const {
      mapPointTocanvas,
      hovered,
      tmpedited,
      tmpdeleted,
      tmpchannels,
      i18n,
    } = this.props

    const resolvePoint = item => {
      if (!item) return null
      const hoverstyle = {
        // width: '100%',
      }
      const { geo, Imei, isMain } = item
      // const p = mapPointTocanvas(geo)
      return (
        <div style={{ ...hoverstyle }}>
          <div style={{ fontSize: 17, fontWeight: 'bold', marginBottom: 10 }}>
            <div>
              <Trans>Device Detail</Trans>:
            </div>{' '}
            <div />
          </div>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            {MakeImeiTag(item)}
          </div>
        </div>
      )
    }

    const resolveLine = item => {
      if (!item) return null
      const hoverstyle = {
        // width: '100%',
      }
      let { geo, Imei, parent, isMain, IsLined, isTmpEdit } = item
      const p = mapPointTocanvas(geo)
      const fromp = MakeImeiTag(item)
      const top = parent && MakeImeiTag(parent)
      const ColorFilter = {
        '0': 'gray',
        '1': '#87d068',
        '-1': '#f50',
        '-2': 'rgb(135,232,222)',
        '-3': 'rgb(250,170,20)',
      }
      const WordsFilter = {
        '0': i18n.t`Unconnected`,
        '1': i18n.t`Connection Successful`,
        '-1': i18n.t`Connection Failed`,
        '-2': i18n.t`Connection Timed Out`,
        '-3': i18n.t`Connecting`,
      }
      const TagFilter = {
        '0': (
          <Tag color="gray">
            <IconFont type="icon-jichuguanli" />
            &nbsp;<Trans>Unconnected</Trans>
          </Tag>
        ),
        '1': (
          <Tag color="#87d068">
            <IconFont type="icon-jichuguanli" />
            &nbsp;<Trans>Connection Successful</Trans>
          </Tag>
        ),
        '-1': (
          <Tag color="#f50">
            <IconFont type="icon-jichuguanli" />
            &nbsp;<Trans>Connection Failed</Trans>
          </Tag>
        ),
        '-2': (
          <Tag color="#f50">
            <IconFont type="icon-jichuguanli" />
            &nbsp;<Trans>Connection Timed Out</Trans>
          </Tag>
        ),
        '-3': (
          <Tag color="rgb(250,170,20)">
            <Icon type="loading" />
            &nbsp;<Trans>Connecting</Trans>
          </Tag>
        ),
      }
      return (
        <div style={{ ...hoverstyle }}>
          <div
            style={{
              fontSize: 17,
              fontWeight: 'bold',
              marginBottom: 10,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <div>
              <Trans>Details of networking</Trans>:
            </div>
            <div style={{ fontSize: 14, fontWeight: 'normal' }}>
              {parent &&
                item &&
                item.geo &&
                parent.geo &&
                getFlatternDistance(
                  parseFloat(item.geo.x),
                  parseFloat(item.geo.y),
                  parseFloat(parent.geo.x),
                  parseFloat(parent.geo.y)
                )}
            </div>
          </div>
          <div>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              {fromp}
            </div>
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                marginTop: 5,
                fontSize: 18,
              }}
            >
              {TagFilter[`${IsLined}`]}
            </div>
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                marginTop: 5,
              }}
            >
              {top}
            </div>
          </div>
          <div
            style={{
              fontSize: 17,
              fontWeight: 'bold',
              marginBottom: 10,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            {/* <div>
              <Trans>Details of networking</Trans>:
            </div> */}
          </div>
        </div>
      )
    }
    var hoverView = undefined
    if (hovered) {
      const { parent } = hovered
      if (parent) {
        hoverView = resolveLine(hovered)
      } else {
        hoverView = resolvePoint(hovered)
      }
    }
    return (
      <Card
        style={{
          width: 180,
          padding: 0,
          position: 'absolute',
          borderStyle: 'solid',
          borderWidth: 1,
          borderRadius: 5,
          borderColor: 'rgb(230,233,237)',
          transition: 'all .5s',
          opacity: hoverView ? 1 : 0,
          background: 'rgba(208,208,208,0.2)',
          top: 5,
        }}
        hoverable
        bodyStyle={{
          padding: 5,
        }}
      >
        {hoverView}
        {/* {hovered ? resolvePoint(hovered) : (hovered_line && resolveLine(hovered_line))} */}
      </Card>
    )
  }
}

const ClickColor = 'rgb(99,133,168)' //167,127,164
const SubPointColor = 'rgb(14,169,226)'
const MainPointColor = 'rgb(48,80,101)'
const RegularLineColor = 'rgb(178,219,205)' //239,168,164
const HoverColor = 'rgb(156,187,254)'
const LinedSuccessColor = 'rgb(152,255,114)' //162,239,83
const LinedSuccessTagColor = 'rgb(76,218,100)' //162,239,83
const TmpLineColor = 'rgb(100,217,126)' //31,136,132
const HandLineColor = 'rgb(69,133,140)'
@withI18n()
@connect(({ app, loading }) => {
  const { clientWidth, clientHeight } = app
  return { clientWidth, clientHeight }
})
class NetWorks extends PureComponent {
  myCanvas = undefined
  // stemp = 0.1
  DOTS = []
  constructor(props) {
    super(props)
    window.NetWorks = this
  }

  state = {
    centerpoint: { x: 0, y: 0 },
    points: [],
    regionPoints: {},
    scal: 0.01,
    offset: { x: 0, y: 0 },
    hovered: undefined,
    lineStart: undefined,
    width: 0,
    height: 0,

    tmpedited: {},
    tmpdeleted: {},
    tmpchannels: {},
    /**
     * 所有操作：
     * 1.连线，
     * 2.删除线
     * 3.设置频道号
     *
     */
    tmpLineTo: undefined,
    tmpLineFrom: undefined,
    ImgMain: undefined,
    ImgSub: undefined,
    // hovered_line: undefined,

    clicked: undefined,
    clickedCenter: { x: 0, y: 0 },

    /**
     * {
     * type: point | line
     *  item: {}
     * }
     */
  }

  componentWillReceiveProps(nextprops, nextstate) {
    const { centerpoint, points, regionPoints } = nextprops
    if (this.refs.canvasContainer) {
      this.setState({
        width: this.refs.canvasContainer.clientWidth,
        height: this.refs.canvasContainer.clientHeight,
      })
    }
    const baseState = { regionPoints, points }
    if (this.props.regionPoints != nextprops.regionPoints) {
      console.log('regionPoints不一致，重新设置hovered')
      const hovered = this.state.hovered
        ? this.state.hovered
        : nextstate.hovered
        ? nextstate.hovered
        : undefined
      if (hovered) {
        const { Imei } = hovered
        for (var ind = 0; ind < points.length; ind++) {
          //let ind = 0; ind < points.length; ind++
          var item = points[ind]
          if (item && item.Imei && Imei == item.Imei) {
            baseState['hovered'] = item
            break
          }
        }
      }

      const clicked = this.state.clicked
        ? this.state.clicked
        : nextstate.clicked
        ? nextstate.clicked
        : undefined
      if (clicked) {
        const { Imei } = clicked
        for (var ind = 0; ind < points.length; ind++) {
          //let ind = 0; ind < points.length; ind++
          var item = points[ind]
          if (item && item.Imei && Imei == item.Imei) {
            baseState['clicked'] = item
            break
          }
        }
      }
    }
    this.setState(
      centerpoint
        ? {
            centerpoint,
            offset: { x: centerpoint.y, y: centerpoint.x },
            ...baseState,
          }
        : { ...baseState },
      () => {
        if (this.refs && this.refs.canvas) {
        }
      }
    )
  }

  componentDidMount() {
    var modal = window.NetWorks

    let { centerpoint, points, regionPoints } = this.props
    regionPoints = regionPoints || {}
    var ImgMain = new Image()
    ImgMain.onload = function() {
      modal.setState({ ImgMain })
    }

    ImgMain.src =
      'http://lc-mocemo7m.cn-n1.lcfile.com/4bf3cb3dc46e1de5227c/%E5%9F%BA%E7%AB%99%E7%AE%A1%E7%90%86.png'

    var ImgSub = new Image()
    ImgSub.onload = function() {
      modal.setState({ ImgSub })
    }
    ImgSub.src =
      'http://lc-mocemo7m.cn-n1.lcfile.com/fce5eeb272eb4f952998/%E8%B7%AF%E7%81%AF.png'

    if (this.refs.canvasContainer) {
      this.setState({
        width: this.refs.canvasContainer.clientWidth,
        height: this.refs.canvasContainer.clientHeight,
      })
    }
    this.setState(
      centerpoint
        ? { centerpoint, regionPoints, points }
        : { regionPoints, points },
      () => {
        var canvas = this.initCanvas()
        if (this.refs && this.refs.canvas) {
        }
      }
    )
  }

  componentWillUnmount() {
    // var modal = window.NetWorks
    if (this.myCanvas) {
      if (this.Onroll)
        this.myCanvas.removeEventListener('mousewheel', this.Onroll)
      if (this.OnMouseDown)
        this.myCanvas.removeEventListener('mousedown', this.OnMouseDown)
      if (this.OnMouseUp)
        this.myCanvas.removeEventListener('mouseup', this.OnMouseUp)
      if (this.OnMouseMove)
        this.myCanvas.removeEventListener('mousemove', this.OnMouseMove)
    }
    this.myCanvas = undefined
    window.NetWorks = undefined
  }
  //#region canvas版本
  initCanvas() {
    var modal = window.NetWorks

    if (!modal.myCanvas) {
      modal.myCanvas = document.getElementById('myCanvas')
      var moveStartOffset = { x: 0, y: 0 }
      var moveType = 0 // 0:不用响应移动，只要检测悬浮 1:移动画布 2:连线
      var startPoint = { x: 0, y: 0 }
      var StartItem = undefined
      var EndItem = undefined
      var downPos = undefined
      modal.Onroll = e => {
        // var event = new Event('mousewheel');//, { bubbles: true }
        // map.dispatchEvent(event, e);

        e = e || window.event
        let { scal } = modal.state
        if (e.wheelDelta) {
          //判断浏览器IE，谷歌滑轮事件
          if (e.wheelDelta > 0) {
            //当滑轮向上滚动时
            scal += 0.01
          }
          if (e.wheelDelta < 0) {
            //当滑轮向下滚动时
            scal -= 0.01
          }
        } else if (e.detail) {
          //Firefox滑轮事件
          if (e.detail > 0) {
            //当滑轮向上滚动时
            scal += 0.01
          }
          if (e.detail < 0) {
            //当滑轮向下滚动时
            scal -= 0.01
          }
        }
        scal = scal <= 0.01 ? 0.01 : scal
        modal.setState({ scal })
        return true
      }
      modal.OnMouseDown = e => {
        // var event = new Event('mousedown');//, { bubbles: true }
        // map.dispatchEvent(event, e);

        moveStartOffset = modal.state.offset
        startPoint = modal.getPointOnCanvas(modal.myCanvas, e)
        // downPos = startPoint
        const hoveredItem = modal.getHoverPoint(startPoint)
        if (hoveredItem) {
          if (hoveredItem.isMain) {
            modal.myCanvas.style.cursor = 'not-allowed'
          } else {
            StartItem = hoveredItem
            const { geo } = StartItem
            modal.setState({ tmpLineFrom: geo })
            moveType = 2
            modal.myCanvas.style.cursor = 'pointer'
            return
          }
        }
        moveType = 1
      }
      modal.OnMouseUp = e => {
        // var event = new Event('mouseup');//, { bubbles: true }
        // map.dispatchEvent(event, e);

        const down = modal.getPointOnCanvas(modal.myCanvas, e)
        const hoveredItem = modal.getHoverPoint(down)
        const { points, regionPoints } = modal.state

        const isclick =
          startPoint &&
          Math.abs(down.x - startPoint.x) < 1 &&
          Math.abs(down.y - startPoint.y) < 1
        var type2Item = {}
        if (!isclick) {
          if (moveType == 2) {
            if (
              hoveredItem &&
              hoveredItem.isMain &&
              StartItem &&
              hoveredItem.Imei !== StartItem.Imei
            ) {
              var isExistsEqual =
                regionPoints &&
                regionPoints[StartItem.Imei] &&
                regionPoints[StartItem.Imei].N &&
                regionPoints[StartItem.Imei].N == hoveredItem.Imei
              //
              if (points && !isExistsEqual) {
                StartItem = {
                  ...StartItem,
                  isTmpEdit: true,
                  parent: {
                    // ...StartItem.parent,
                    // Imei: hoveredItem.Imei,
                    // geo: hoveredItem.geo,
                    ...hoveredItem,
                  },
                }
                modal.state.tmpedited[StartItem.Imei] = { ...StartItem }
                type2Item = { tmpedited: { ...modal.state.tmpedited } }
              }
            }
            StartItem = undefined
          }
        }

        modal.setState({
          tmpLineTo: undefined,
          tmpLineFrom: undefined,
          ...type2Item,
        })

        if (hoveredItem) {
          if (isclick) {
            modal.setState({
              clicked: hoveredItem,
            })
          }
          if (hoveredItem.isMain) {
            modal.myCanvas.style.cursor = 'not-allowed'
          } else {
            modal.myCanvas.style.cursor = 'pointer'
          }
        } else {
          const hovered = modal.gethoverLine(down)

          if (modal.state.hovered !== hovered) {
            modal.setState({ hovered })
          }
          if (hovered) {
            if (isclick) {
              modal.setState({
                clicked: hovered,
              })
            }
            modal.myCanvas.style.cursor = 'pointer'
          } else {
            modal.myCanvas.style.cursor = '-webkit-grab'
          }
        }
        moveType = 0
      }
      modal.OnMouseMove = e => {
        // var event = new Event('mousemove', { bubbles: true });//, { bubbles: true }
        // map.dispatchEvent(event, e);

        var down = modal.getPointOnCanvas(modal.myCanvas, e)
        if (moveType == 1) {
          let centerx = startPoint.x,
            centery = startPoint.y
          var targoffX =
            moveStartOffset.x + (centerx - down.x) / 1000000 / modal.state.scal
          var targoffY =
            moveStartOffset.y - (centery - down.y) / 1000000 / modal.state.scal
          modal.setState({ offset: { x: targoffX, y: targoffY } })
        } else if (moveType == 2) {
          modal.setState({ tmpLineTo: modal.canvasPointTomap(down) })
        }
        const hoveredItem = modal.getHoverPoint(down)
        if (modal.state.hovered !== hoveredItem) {
          //|| (modal.state.hovered.Imei != hoveredItem.Imei)
          modal.setState({ hovered: hoveredItem })
        }

        if (hoveredItem) {
          if (hoveredItem.isMain) {
            modal.myCanvas.style.cursor = 'not-allowed'
          } else {
            modal.myCanvas.style.cursor = 'pointer'
          }
        } else {
          const hovered = modal.gethoverLine(down)

          if (modal.state.hovered !== hovered) {
            modal.setState({ hovered })
          }
          if (hovered) {
            modal.myCanvas.style.cursor = 'pointer'
          } else {
            modal.myCanvas.style.cursor = '-webkit-grab'
          }
        }
      }
      modal.myCanvas.addEventListener('mousewheel', modal.Onroll, false)
      modal.myCanvas.addEventListener('mousedown', modal.OnMouseDown, false)
      modal.myCanvas.addEventListener('mouseup', modal.OnMouseUp, false)
      modal.myCanvas.addEventListener('mousemove', modal.OnMouseMove, false)
      // modal.myCanvas
    }
    return modal.myCanvas
  }

  draw() {
    var modal = window.NetWorks
    // const {hovered} = modal.state
    modal.initCanvas()
    var ctx = modal.myCanvas.getContext('2d')
    ctx.clearRect(0, 0, modal.props.clientWidth, modal.props.clientHeight)
    modal.initLines()
    modal.initPoints()
  }

  initLines() {
    var modal = window.NetWorks
    var ctx = modal.myCanvas.getContext('2d')
    const { points, tmpLineFrom, tmpLineTo, tmpedited } = modal.state

    for (var ind = 0; ind < points.length; ind++) {
      var item = points[ind]
      const { parent } = item
      if (parent) {
        const { Imei, geo } = parent
        // modal.drawArrow(
        //   ctx,
        //   modal.mapPointTocanvas(item.geo),
        //   modal.mapPointTocanvas(geo)
        // )
        modal.drawLine(
          ctx,
          modal.mapPointTocanvas(item.geo),
          modal.mapPointTocanvas(geo),
          { item }
        )
      }
    }
    for (var Imei in tmpedited) {
      const item = tmpedited[Imei]
      if (item && item.parent) {
        const { parent } = item
        const { geo } = parent
        // modal.drawArrow(
        //   ctx,
        //   modal.mapPointTocanvas(item.geo),
        //   modal.mapPointTocanvas(geo),
        //   { istmp: true, item }
        // )
        modal.drawLine(
          ctx,
          modal.mapPointTocanvas(item.geo),
          modal.mapPointTocanvas(geo),
          { item, istmp: true }
        )
      }
    }
    if (tmpLineFrom && tmpLineTo) {
      modal.drawArrow(
        ctx,
        modal.mapPointTocanvas(tmpLineFrom),
        modal.mapPointTocanvas(tmpLineTo),
        { isbyHand: true }
      )
      modal.drawLine(
        ctx,
        modal.mapPointTocanvas(tmpLineFrom),
        modal.mapPointTocanvas(tmpLineTo),
        { isbyHand: true }
      )
    }
  }

  drawArrow(ctx, from, to, others) {
    return
    const { istmp, isbyHand } = others || {}
    const fromX = from.x,
      fromY = from.y
    const toX = to.x,
      toY = to.y
    var theta = 30,
      headlen = 10

    var width = 1,
      color = '#000'
    if (istmp) {
      headlen = 20
      width = 1
      color = 'rgb(169,183,169)'
    } else if (isbyHand) {
      headlen = 10
      width = 1
      color = 'rgb(169,183,169)'
    } else {
      width = 2
      color = 'rgb(41,153,255)'
    }

    var angle = (Math.atan2(fromY - toY, fromX - toX) * 180) / Math.PI,
      angle1 = ((angle + theta) * Math.PI) / 180,
      angle2 = ((angle - theta) * Math.PI) / 180,
      topX = headlen * Math.cos(angle1),
      topY = headlen * Math.sin(angle1),
      botX = headlen * Math.cos(angle2),
      botY = headlen * Math.sin(angle2)

    ctx.save()
    ctx.beginPath()
    var arrowX, arrowY
    // ctx.moveTo(fromX, fromY);
    // ctx.lineTo(toX, toY);
    arrowX = toX + topX
    arrowY = toY + topY
    ctx.moveTo(arrowX, arrowY)
    ctx.lineTo(toX, toY)
    arrowX = toX + botX
    arrowY = toY + botY
    ctx.lineTo(arrowX, arrowY)
    ctx.strokeStyle = color
    ctx.lineWidth = width
    ctx.stroke()
    ctx.restore()
  }

  isSameLine(line, target, istmp, isclick) {
    return istmp
      ? target && line && target.isTmpEdit && line.Imei == target.Imei
      : target &&
          line &&
          line.Imei == target.Imei &&
          (line.parent &&
            target.parent &&
            line.parent.Imei == target.parent.Imei)
  }

  drawLine(ctx, from, to, others) {
    var modal = window.NetWorks
    const { hovered, clicked } = modal.state

    const { isbyHand, istmp, item } = others ? others : {}
    ctx.beginPath()
    ctx.moveTo(from.x, from.y)
    ctx.lineTo(to.x, to.y)
    if (isbyHand) {
      ctx.lineWidth = 2
      ctx.setLineDash([5])
      ctx.strokeStyle = HandLineColor //'rgb(170,183,196)'
    } else if (istmp) {
      ctx.lineWidth = 2
      ctx.setLineDash([5])
      ctx.strokeStyle = TmpLineColor //'rgb(62,176,144)'
    } else {
      const { IsLined } = item
      ctx.lineWidth = 2
      ctx.setLineDash([])
      ctx.strokeStyle = IsLined == '1' ? LinedSuccessColor : RegularLineColor //'rgb(61,162,255)' : 'rgb(168,218,146)'
    }
    ctx.shadowOffsetX = 0
    ctx.shadowOffsetY = 0
    ctx.shadowBlur = 0
    if (modal.isSameLine(item, clicked, istmp, true)) {
      //clicked &&
      ctx.strokeStyle = ClickColor //'rgb(156,46,217)'//
      ctx.lineWidth = 3
    } else if (modal.isSameLine(item, hovered, istmp)) {
      ctx.strokeStyle = HoverColor //'rgb(62,76,114)'
      ctx.shadowColor = 'rgba(48,48,48,1)'
      ctx.shadowOffsetX = 0
      ctx.shadowOffsetY = 0
      ctx.shadowBlur = 3
    }
    ctx.stroke()
  }

  gethoverLine(down) {
    var modal = window.NetWorks
    var ctx = modal.myCanvas.getContext('2d')
    const { points, tmpedited } = modal.state
    for (var ind = 0; ind < points.length; ind++) {
      var item = points[ind]
      const { parent } = item
      if (parent) {
        const { Imei, geo } = parent
        ctx.save()
        const isin = modal.isPointInLine(
          ctx,
          down,
          modal.mapPointTocanvas(item.geo),
          modal.mapPointTocanvas(geo)
        )
        if (isin) {
          //ctx.isPointInPath(down.x, down.y)
          ctx.restore()
          return item
        }
      }
    }
    for (var Imei in tmpedited) {
      const item = tmpedited[Imei]
      if (item && item.parent) {
        const { parent } = item
        const { geo } = parent
        ctx.save()
        const isin = modal.isPointInLine(
          ctx,
          down,
          modal.mapPointTocanvas(item.geo),
          modal.mapPointTocanvas(geo),
          { istmp: true }
        )
        if (isin) {
          //ctx.isPointInPath(down.x, down.y)
          ctx.restore()
          return item
        }
      }
    }
    return undefined
  }

  isPointInLine(ctx, down, from, to) {
    const padding = 5
    ctx.lineWidth = 20
    ctx.beginPath()
    ctx.moveTo(from.x, from.y - padding)
    ctx.lineTo(from.x, from.y + padding)
    ctx.lineTo(to.x, to.y + padding)
    ctx.lineTo(to.x, to.y - padding)
    ctx.lineTo(from.x, from.y - padding)
    ctx.closePath()
    if (ctx.isPointInPath(down.x, down.y)) {
      ctx.restore()
      return true
    }
    ctx.beginPath()
    ctx.moveTo(from.x - padding, from.y)
    ctx.lineTo(from.x + padding, from.y)
    ctx.lineTo(to.x + padding, to.y)
    ctx.lineTo(to.x - padding, to.y)
    ctx.lineTo(from.x - padding, from.y)
    ctx.closePath()
    if (ctx.isPointInPath(down.x, down.y)) {
      ctx.restore()
      return true
    }
    return false
  }

  initPoints() {
    var modal = window.NetWorks
    const { points, centerpoint, hovered, tmpLineTo } = modal.state
    var ctx = modal.myCanvas.getContext('2d')
    for (var ind = 0; ind < points.length; ind++) {
      var item = points[ind]
      if (item) {
        const { isMain, Imei, geo } = item
        const ishover = hovered && Imei == hovered.Imei
        modal.drawPoint(ctx, modal.mapPointTocanvas(geo), {
          isMain,
          ishover,
          item,
        })
      }
    }
  }

  getPointRadius(isMain) {
    return isMain ? 15 : 12
  }

  drawPoint(ctx, point, others) {
    var modal = window.NetWorks
    const { ImgMain, ImgSub, clicked } = modal.state
    const { isMain, ishover, item } = others ? others : {}
    var radius = modal.getPointRadius(isMain) // ? 20 : 15
    const width = modal.refs.canvas.clientWidth
    const height = modal.refs.canvas.clientHeight
    if (
      !(
        point.x >= -radius / 2 &&
        point.x < width + radius / 2 &&
        point.y >= -radius / 2 &&
        point.y <= height + radius / 2
      )
    ) {
      return
    }
    ctx.beginPath()
    ctx.arc(point.x, point.y, radius, 0, 2 * Math.PI)
    ctx.fillStyle = isMain ? MainPointColor : SubPointColor // 'rgb(116,196,254)' //'rgb(62,76,114)'
    ctx.shadowOffsetX = 0
    ctx.shadowOffsetY = 0
    ctx.shadowBlur = 0
    ctx.fill()

    if (ishover) {
      ctx.beginPath()
      ctx.arc(point.x, point.y, radius, 0, 2 * Math.PI)
      ctx.fillStyle = 'rgba(255,255,255,0.5)'
      ctx.fill()

      ctx.beginPath()
      ctx.arc(point.x, point.y, radius + 1, 0, 2 * Math.PI)
      ctx.strokeStyle = HoverColor //'rgba(78,154,217,1)'
      ctx.shadowColor = 'rgba(48,48,48,1)'
      ctx.shadowOffsetX = 0
      ctx.shadowOffsetY = 0
      ctx.shadowBlur = 5
      ctx.lineWidth = 2
      ctx.setLineDash([])
      ctx.stroke()
    }

    if (clicked && item && clicked.Imei == item.Imei) {
      ctx.beginPath()
      ctx.arc(point.x, point.y, radius + 1, 0, 2 * Math.PI)
      ctx.strokeStyle = ClickColor //ClickColor//'rgb(168,218,146)'
      ctx.shadowOffsetX = 0
      ctx.shadowOffsetY = 0
      ctx.shadowBlur = 0
      ctx.lineWidth = 2
      ctx.setLineDash([])
      ctx.stroke()
    }

    const imgwidth = radius + 4
    if (isMain) {
      if (ImgMain) {
        ctx.drawImage(
          ImgMain,
          point.x - imgwidth / 2,
          point.y - imgwidth / 2,
          imgwidth,
          imgwidth
        )
      }
    } else {
      if (ImgSub) {
        ctx.drawImage(
          ImgSub,
          point.x - imgwidth / 2,
          point.y - imgwidth / 2,
          imgwidth,
          imgwidth
        )
      }
    }
    // ctx.font = "10px Arial";
    // ctx.fillText(JSON.stringify(point), point.x, point.y);
  }

  mockdrawPoint(ctx, point, others) {
    const { isMain } = others ? others : {}
    var modal = window.NetWorks
    ctx.beginPath()
    ctx.arc(point.x, point.y, modal.getPointRadius(isMain), 0, 2 * Math.PI)
  }

  getHoverPoint(down) {
    var modal = window.NetWorks
    const { points } = modal.state
    var ctx = modal.myCanvas.getContext('2d')
    for (var ind = 0; ind < points.length; ind++) {
      //let ind = 0; ind < points.length; ind++
      var item = points[ind]
      if (item) {
        const { isMain, Imei, geo } = item
        ctx.save()
        var mockp = modal.mapPointTocanvas(geo)
        if (
          (mockp.x >= 0 && mockp.y >= 0 && Math.abs(mockp.x - down.x) <= 20) ||
          Math.abs(mockp.y - down.y) <= 20
        ) {
          modal.mockdrawPoint(ctx, mockp, { isMain })
          if (ctx.isPointInPath(down.x, down.y)) {
            ctx.restore()
            return item
          }
        }
      }
    }
    return undefined
  }

  canvasPointTomap(point) {
    var modal = window.NetWorks
    const { scal, offset } = modal.state
    let centerx = 0,
      centery = 0
    if (modal.refs && modal.refs.canvas) {
      centerx = modal.refs.canvas.clientWidth / 2
      centery = modal.refs.canvas.clientHeight / 2
    }
    if (point) {
      const { x, y } = point
      var maskx = (x - centerx) / 1000000 / scal + offset.x
      var masky = (centery - y) / 1000000 / scal + offset.y
      return { x: masky, y: maskx }
    } else {
      return point
    }
  }

  mapPointTocanvas(point) {
    var modal = window.NetWorks
    const { scal, offset } = modal.state
    // const {clientWidth, clientHeight } = modal.props
    let centerx = 0,
      centery = 0
    if (modal.refs && modal.refs.canvas) {
      centerx = modal.refs.canvas.clientWidth / 2
      centery = modal.refs.canvas.clientHeight / 2
    }
    if (point) {
      const { x, y } = point
      var maskx = y
      var masky = x
      var truex = (maskx - offset.x) * 1000000 * scal + centerx
      var truey = centery - (masky - offset.y) * 1000000 * scal
      return { x: truex, y: truey }
    } else {
      return point
    }
  }
  //决定缩放比例
  getPointOnCanvas(canvas, e) {
    var x = e.pageX
    var y = e.pageY
    var bbox = canvas.getBoundingClientRect()
    return {
      x: x - bbox.left * (canvas.width / bbox.width),
      y: y - bbox.top * (canvas.height / bbox.height),
    }
  }
  //#endregion

  //#region map版本
  xArr = 0 //存放横坐标
  yArr = 0 //存放纵坐标
  endx = 0
  endy = 0
  moved = false
  setMarks(points) {
    const modal = window.NetWorks
    var map = modal.initMap()
    map.clearOverlays()
    const makeSubMark = (key, item) => {
      const { G, O } = item
      let geo = G.split(',')
      var tmppoint = new BMap.Point(parseFloat(geo[1]), parseFloat(geo[0]))
      var p = new BMap.Marker(tmppoint)
      return p
    }
    const makeMainMark = (key, item) => {
      const { G, O } = item
      let geo = G.split(',')
      var tmppoint = new BMap.Point(parseFloat(geo[1]), parseFloat(geo[0]))
      var p = new BMap.Marker(tmppoint)
      p.addEventListener('onmousedown', function(e) {
        console.log('onmousedown')
      })
      p.addEventListener('click', function(e) {
        console.log('click')
        const { choosedDevice1, choosedDevice2 } = modal.state
        if (!choosedDevice1) {
          modal.setState({ choosedDevice1: item })
        } else if (!choosedDevice2) {
          modal.setState({ choosedDevice2: item })
        } else {
          alert('都满了')
        }
      })
      // choosedDevice1
      return p
    }
    for (let key in points) {
      // console.log(key)
      if (key) {
        let item = points[key]
        if (item && item.G) {
          map.addOverlay(
            key.indexOf(':E:') >= 0
              ? makeSubMark(key, item)
              : makeMainMark(key, item)
          )
        }
      }
    }
  }
  centerAndZoom = value => {
    const modal = window.NetWorks
    var map = modal.initMap()
    if (value) {
      map.centerAndZoom(new BMap.Point(value.lng, value.lat), 15)
      modal.choosePoint(value, map)
    }
  }
  initMap() {
    const modal = window.NetWorks

    var map = undefined
    const initcontrols = () => {
      var opts = { anchor: BMAP_ANCHOR_BOTTOM_RIGHT }
      map.enableScrollWheelZoom(true)
      map.addControl(new BMap.MapTypeControl())
      map.addControl(new BMap.ScaleControl(opts))
      map.addControl(new BMap.NavigationControl())

      map.addEventListener('touchstart', function(e) {
        //手指触摸屏幕的时候清空两个数组
        // message.info('blur')
        if (modal.inputref) modal.inputref.blur()
        if (modal.inputref2) modal.inputref2.blur()
        if (modal.inputref3) modal.inputref3.blur()
        modal.moved = false
        modal.xArr = e.targetTouches[0].pageX
        modal.yArr = e.targetTouches[0].pageY
        modal.endx = e.targetTouches[0].pageX
        modal.endy = e.targetTouches[0].pageY
      })

      map.addEventListener('touchmove', function(e) {
        //如果滑动了屏幕，xArr和yArr将各存入两个坐标值，即始末坐标值
        // xArr.push(e.targetTouches[0].pageX);
        // yArr.push(e.targetTouches[0].pageY);
        // message.info("touchmove")
        modal.moved = true
        modal.endx = e.targetTouches[0].pageX
        modal.endy = e.targetTouches[0].pageY
      })

      map.addEventListener('touchend', function(e) {
        // var endx = e.targetTouches[0].pageX
        // var endy = e.targetTouches[0].pageY
        var far
        var flag = true
        //计算平移距离，区分滑动事件和点击事件
        // if ((xArr> 1) && (yArr.length > 1)) {
        far =
          Math.abs(modal.xArr - modal.endx) ^
          (2 + Math.abs(modal.yArr - modal.endy)) ^
          2
        if (far > 0) {
          flag = false
        }
        // }
        if (flag) {
          // modal.choosePoint(e.point, map)
        }
      })

      map.addEventListener('click', function(e) {
        console.log('click')
        console.log(e)
        // modal.choosePoint(e.point, map)
      })

      var geolocationControl = new BMap.GeolocationControl(opts)
      geolocationControl.addEventListener('click', function(e) {
        console.log(e)
      })
      geolocationControl.addEventListener('locationSuccess', function(e) {
        modal.centerAndZoom(e.target.xD)
      })
      geolocationControl.addEventListener('locationError', function(e) {
        alert(e.message)
      })
      map.addControl(geolocationControl)
    }
    if (modal.map) {
      map = modal.map
    } else {
      map = new BMap.Map('loras_allmap')
      initcontrols()
    }
    modal.map = map
    return map
  }
  //#endregion

  render() {
    const { clientWidth, clientHeight, dispatch, i18n } = this.props
    const {
      width,
      height,
      scal,
      hovered,
      tmpedited,
      tmpdeleted,
      tmpchannels,
      centerpoint,
      clicked,
    } = this.state
    // const {points} = this.state
    //#region canvas版本
    if (this.myCanvas) this.draw()
    const clearedit = items => {
      if (items) {
        for (var Imei in items) {
          delete tmpedited[Imei]
        }
        this.setState({ tmpedited: { ...tmpedited } })
      } else {
        this.setState({ tmpedited: {} })
      }
    }

    const onSetNetwork = items => {
      dispatch({
        type: `loras/setNetWork`,
        payload: { targets: JSON.stringify(items) },
      })
        .then(successed => {
          clearedit(items)
          dispatch({ type: `loras/query` })
        })
        .catch(error => {})
    }

    const onDeleteLine = item => {
      //这里需要判断下是否是tmplined
      const { isTmpEdit, Imei } = item || {}
      if (isTmpEdit) {
        delete tmpedited[Imei]
        this.setState({
          tmpedited: { ...tmpedited },
        })
      } else {
        const payload = {}
        payload[Imei] = item
        dispatch({
          type: `loras/delNetWork`,
          payload: {
            targets: JSON.stringify(payload),
          },
        })
          .then(successed => {
            // clearedit(payload)
            dispatch({ type: `loras/query` })
          })
          .catch(error => {})
        // this.setState({ tmpdeleted: tmpdeleted.push(item) })
      }
    }

    const onHover = item => {
      this.setState({ hovered: item })
    }
    //#endregion
    return (
      <Fragment>
        <Toolbox
          {...{
            tmpedited,
            scal,
            onSetNetwork,
            changescal: sc => {
              this.setState({ scal: sc })
            },
            clearedit,
            relocation: () => {
              this.setState({
                offset: { x: centerpoint.y, y: centerpoint.x },
              })
            },
          }}
        />
        <div
          // onSelect={e => {
          //   document.getSelection().empty()
          // }}
          // onCopy={() => {
          //   if (document.getSelection()) document.getSelection().empty()
          //   return false
          // }}
          // onMouseUp={e => {
          //   document.getSelection().empty()
          // }}
          // onMouseDown={e => {
          //   document.getSelection().empty()
          // }}
          // onDragStart={e => {
          //   document.getSelection().empty()
          //   return false
          // }}
          // onSelectCapture={e => {
          //   document.getSelection().empty()
          // }}
          style={{ display: 'flex' }}
        >
          <div
            ref="canvasContainer"
            style={{
              width: '100%',
              minHeight: 500,
              height: 'calc(100vh - 320px)',
              position: 'relative',
            }}
          >
            {/* <div
              id="loras_allmap"
              style={{
                width: width - 5,
                height: height - 50,
              }}
            /> */}
            <canvas
              id="myCanvas"
              ref="canvas"
              width={width - 5}
              height={height - 50}
              style={{ position: 'absolute' }}
            />
            <StatusBoard
              {...{
                hovered,
                clicked,
                tmpedited,
                tmpdeleted,
                tmpchannels,
                mapPointTocanvas: this.mapPointTocanvas,
                onDeleteLine,
                onHover,
                onSetChannel: item => {
                  this.setState({})
                },
                onDeleteTmpChannel: item => {},
                onSetLine: item => {
                  dispatch({ type: `loras/setline` })
                },
              }}
            />
          </div>
          <SideBar
            {...{
              hovered,
              clicked,
              tmpedited,
              tmpdeleted,
              tmpchannels,
              mapPointTocanvas: this.mapPointTocanvas,
              //
              onDeleteLine,
              onSetNetwork,
              onHover,
              clearedit,
              onSetChannel: item => {
                this.setState({})
              },
              onDeleteTmpChannel: item => {},
              onSetLine: item => {
                dispatch({ type: `loras/setline` })
              },
            }}
          />
        </div>
      </Fragment>
    )
  }
}

export default NetWorks
